"""
@author: zwz
@file: 14.实现链表反转.py
@time: 2022/12/7 0007 15:05:18
"""

class ListNode:
    def __init__(self, elem):
        self.elem = elem
        self.next = None

def reverseList(head):
    # 若链表为空或者仅一个数直接饭后
    if head == None or head.next == None:
        return head
    pre = None
    next = None
    while(head != None):
        # 将 head.next 赋值给 next 变量，即next 指向了节点2，先将节点2 保存起来。
        next = head.next
        # 将 pre 变量赋值给 head.next，即 此时节点1 指向了 None
        head.next = pre
        # 将 head 赋值给了 pre，即 pre 指向节点1，将节点1 设为“上一个节点”
        pre = head
        # 将 next 赋值给 head，即 head 指向了节点2，此时节点2 设为“头节点”
        head = next
    return pre

# 构建链表
l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(3)
l1.next.next.next = ListNode(4)
l1.next.next.next.next = ListNode(5)

l = reverseList(l1)

while l.next != None:
    print(l.elem)
    l = l.next
print(l.elem)


